import { useState, useEffect } from 'react';
import axios from 'axios';


const useAxios = () => {
    const [data, setData] = useState(null);
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState(null);

    const axiosInstance = axios.create({
        baseURL: '',
    });

    axiosInstance.interceptors.request.use((config) => {
        setLoading(true);
        return config;
    });

    axiosInstance.interceptors.response.use(
        (response) => {
            setLoading(false);
            setData(response.data);
            return response;
        },
        (error) => {
            setLoading(false);
            setError(error.response.data);
            throw error;
        }
    );

    const sendRequest = async (config) => {
        try {
            const response = await axiosInstance(config);
            setData(response.data);
            return response;
        } catch (error) {
            setError(error.response.data);
            throw error;
        }
    };
    const get = async (url, config) => {
        const response = await sendRequest({ method: 'get', url, ...config });
        return response.data;
    };

    const post = async (url, data, config) => {
        const response = await sendRequest({
            method: 'post',
            url,
            data,
            ...config,
        });
        return response.data;
    };

    return { data, loading, error, sendRequest,get,post };
};

export default useAxios;
